package com.hsnn.medstgmini.base.dict.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicCompType;
import com.hsnn.medstgmini.base.dict.service.DicCompTypeManager;
import com.hsnn.medstgmini.filter.AuthFilter;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.ExcelUtil;
import com.hsnn.medstgmini.util.Pagination;

@Controller
@RequestMapping("/dicCompType")
public class DicCompTypeController {
	
	private static final Logger log = Logger.getLogger(AuthFilter.class);
	
	@Autowired
	private DicCompTypeManager dicCompTypeManager;
	
	@Autowired
	private HttpServletRequest request;
	
	public DicCompTypeManager getDicCompTypeManager() {
		return dicCompTypeManager;
	}
	public void setDicCompTypeManager(DicCompTypeManager dicCompTypeManager) {
		this.dicCompTypeManager = dicCompTypeManager;
	}

	/**
	 * 企业注册类型(列表)查看
	 */
	@RequestMapping("/dicCompTypeList")
	public String dicCompTypeList(Model model) {
		/*List<DicCompType> list = dicCompTypeManager.getDicCompTypeFullList();
		model.addAttribute("list", list);*/
		return "/base/dict/compTypeList";
	}
	
	@RequestMapping("/getCompTypeList")
	@ResponseBody
	public Pagination getCompTypeList(){
		printParams();
		Pagination page = new Pagination(request);
		if(StringUtils.isNotBlank(request.getParameter("compRegCode"))){
			page.getConditions().put("compRegCode", request.getParameter("compRegCode"));
		}
		if(StringUtils.isNotBlank(request.getParameter("compRegName"))){
			page.getConditions().put("compRegName", request.getParameter("compRegName"));
		}
		if(StringUtils.isNotBlank(request.getParameter("status"))){
			page.getConditions().put("status", request.getParameter("status"));
		}
		try {
			dicCompTypeManager.getDicCompTypeList(page);
		} catch (Exception e) {
			log.error("dicCompTypeList view",e);
		}
		return page;
	}
	
	
	
	
	
	
	/**
	 * 
	 *@category 批量启用停用
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(String array) {
		printParams();
		Pagination page = new Pagination();
		int count = 0;
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		try {
			if (StringUtils.isNotBlank(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<DicCompType>>() {
				}.getType();
				List<DicCompType> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					for (DicCompType dds : list) {
						dds.setUpdUser(user.getId());
						count += dicCompTypeManager.changeStatus(dds);
					}
					page.setSuccess(true);
					page.getConditions().put("count", count+"");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	
	
	/**
	 * 
	 *@category 查询编辑数据
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping("initEdit")
	@ResponseBody
	public Pagination initEdit() {
		printParams();
		Pagination page = new Pagination();
		if(StringUtils.isNotBlank(request.getParameter("compRegId"))){
			page.getConditions().put("compRegId", request.getParameter("compRegId").trim());
		}
		try {
			page = dicCompTypeManager.initEdit(page);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 新增或编辑剂型
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping(value={"/add","/edit","/addTwo"})
	@ResponseBody
	public Pagination dicComptypeUpdate() {
		printParams();
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		page.getConditions().put("updUser", user.getId());
		if(StringUtils.isNotBlank(request.getParameter("compRegCode"))){
			page.getConditions().put("compRegCode", request.getParameter("compRegCode").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("compRegName"))){
			page.getConditions().put("compRegName", request.getParameter("compRegName").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("compRegId"))){
			page.getConditions().put("compRegId", request.getParameter("compRegId").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("remark"))){
			page.getConditions().put("remark", request.getParameter("remark").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("fatherId"))){
			page.getConditions().put("fatherId", request.getParameter("fatherId").trim());
		}else{
			page.getConditions().put("fatherId", "0");
		}
		try {
			if(request.getParameter("compRegId")!=null){
				if(StringUtils.isNotBlank(request.getParameter("compRegId"))){
					DicCompType dicCompType = dicCompTypeManager.getDicCompTypeById(page.getConditions().get("compRegId"));
					if(dicCompType.getCompRegCode().equals(page.getConditions().get("compRegCode"))&&dicCompType.getCompRegName().equals(page.getConditions().get("compRegName"))&&dicCompType.getRemark().equals(page.getConditions().get("remark"))){
						page.setMsg("数据未做任何修改，不能保存!");
	            		 page.setSuccess(false);
	            		 return page;
					}
					//update
					if(StringUtils.isNotBlank(request.getParameter("compRegCode"))){
		            	List<DicCompType> list=dicCompTypeManager.getCompTypeBy("comp_reg_code",request.getParameter("compRegCode").trim(),request.getParameter("compRegId"));
		            	 if(list.size()>0){
		            		 page.setMsg("企业类型编码已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入企业类型编码!");
		            	page.setSuccess(false);
		            	return page;
		            }
		            if(StringUtils.isNotBlank(request.getParameter("compRegName").trim())){
		            	List<DicCompType> list=dicCompTypeManager.getCompTypeBy("comp_reg_name",request.getParameter("compRegName").trim(),request.getParameter("compRegId"));
		            	 if(list.size()>0){
		            		 page.setMsg("企业类型名称已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入企业类型名称!");
		            	page.setSuccess(false);
		            	return page;
		            }
					dicCompTypeManager.updateCompType(page);
					page.setMsg("修改成功!");
					page.setSuccess(true);
				}else{
					//add
					if(StringUtils.isNotBlank(request.getParameter("compRegCode"))){
		            	List<DicCompType> list=dicCompTypeManager.getCompTypeBy("comp_reg_code",request.getParameter("compRegCode").trim(),"");
		            	 if(list.size()>0){
		            		 page.setMsg("企业类型已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入企业类型!");
		            	page.setSuccess(false);
		            	return page;
		            }
		            if(StringUtils.isNotBlank(request.getParameter("compRegName").trim())){
		            	List<DicCompType> list=dicCompTypeManager.getCompTypeBy("comp_reg_code",request.getParameter("compRegName").trim(),"");
		            	 if(list.size()>0){
		            		 page.setMsg("企业类型已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入企业类型名称!");
		            	page.setSuccess(false);
		            	return page;
		            }
		            String compTypeAddId = UUID.randomUUID().toString();
		            page.getConditions().put("compTypeAddId", compTypeAddId);
		            if(!"0".equals(request.getParameter("fatherId"))){
		            	dicCompTypeManager.addCompType(page);
						page.setMsg("保存成功!");
						page.setSuccess(true);
		            }else{
		            	if(StringUtils.isNotBlank(request.getParameter("oCompRegCode"))){
		            		page.getConditions().put("compRegCode", request.getParameter("oCompRegCode").trim());
		            		page.getConditions().put("compRegName", request.getParameter("oCompRegCode").trim());
		            		page.getConditions().put("remark", request.getParameter("oRemark").trim());
		            		dicCompTypeManager.addCompType(page);
		            		page.getConditions().put("compRegCode", request.getParameter("compRegCode").trim());
		            		page.getConditions().put("compRegName", request.getParameter("compRegName").trim());
		            		page.getConditions().put("remark", request.getParameter("remark").trim());
		            		page.getConditions().put("compTypeAddId", UUID.randomUUID().toString());
		            		page.getConditions().put("fatherId", compTypeAddId);
		            		dicCompTypeManager.addCompType(page);
							page.setMsg("保存成功!");
							page.setSuccess(true);
		            	}else{
		            		dicCompTypeManager.addCompType(page);
							page.setMsg("保存成功!");
							page.setSuccess(true);
		            	}
		            }
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			page.setMsg("保存失败!");
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 检查是否重复
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping("checkRepeat")
	@ResponseBody
	public Pagination checkRepeat() {
		printParams();
		Pagination page = new Pagination();
		String compRegCode = request.getParameter("compRegCode");
		String compRegName = request.getParameter("compRegName");
		
		try {
			 if(StringUtils.isNotBlank(compRegCode)){
	            	List<DicCompType> list=dicCompTypeManager.getCompTypeBy("comp_reg_code",compRegCode.trim(),"");
	            	 if(list.size()>0){
	            		 page.setMsg("企业类型编码已存在!");
	            		 page.setSuccess(false);
	            		 return page;
	                 }else{
	                	 page.setSuccess(true);
	                 }
	            }else{
	            	page.setMsg("请输入企业类型编码!");
	            	page.setSuccess(false);
	            	return page;
	            }
	            if(StringUtils.isNotBlank(compRegName)){
	            	List<DicCompType> list=dicCompTypeManager.getCompTypeBy("comp_reg_name",compRegName.trim(),"");
	            	 if(list.size()>0){
	            		 page.setMsg("企业类型名称已存在!");
	            		 page.setSuccess(false);
	            		 return page;
	                 }else{
	                	 page.setSuccess(true);
	                 }
	            }else{
	            	page.setMsg("请输入企业类型名称!");
	            	page.setSuccess(false);
	            	return page;
	            }
			
		} catch (Exception e) {
			e.printStackTrace();
			page.setMsg(e.toString());
			page.setSuccess(false);
		}
		return page;
	}
	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	/**
	 * 
	 *@category 导出excel
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String compRegCode = request.getParameter("compRegCode");
		String compRegName = request.getParameter("compRegName");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(compRegCode)){
			page.getConditions().put("compRegCode", compRegCode.trim());
		}
		if(StringUtils.isNotBlank(compRegName)){
			page.getConditions().put("compRegName", compRegName.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			 dicCompTypeManager.getDicCompTypeNoPage(page);
			 String title = "企业注册类型";
			 String[] headers = {"一级编码","一级名称","二级编码","二级名称","状态","备注"};
			 String[] alias = {"fatherCompRegCode","fatherCompRegName","compRegCode","compRegName","status","remark"};
			 ExcelUtil.exportExcel(page, os, title, headers, alias);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}
